const { typeOf, needParam } = require("../../utils");
const getFormFieldsTpls = require("../../template/form-items");
const { merge, upperFirst } = require("lodash");
const tableColsTpls = require("../../template/table-cols");
const { defaultFormItemType } = require("./_consts");

module.exports = {
  /**
   * 获取标准的 BaseForm 的fields
   * @param {(string|object)[]} simpleFields 简版field
   * @returns {(string|object)[]}
   * @example ["remark", "enableStatus:status", "createTime", {tpl: 'remark'}]
   */
  getFormStandardFields(simpleFields = needParam(), type = "common") {
    const tpls = getFormFieldsTpls(type);
    return simpleFields.map(sField => {
      const t = typeOf(sField);
      if (t === "String") {
        const [tpl, prop = tpl, label, compType = defaultFormItemType] = sField.split(":");
        const Tpl = `T_${upperFirst(tpl)}`;
        return merge(tpls[Tpl], { prop, label, type: compType });
      } else if (t === "Object") {
        const { tpl = "", prop = tpl, type: compType = defaultFormItemType, ...rest } = sField;
        const Tpl = `T_${upperFirst(tpl)}`;
        if (tpl) {
          if (!tpls[Tpl]) throw new Error(`未找到该模板：${tpl}`);
        } else {
          if (!prop) throw new Error(`不能同时不传tpl和prop参数`);
        }
        return merge(tpls[Tpl], { prop, type: compType }, rest);
      } else {
        throw new Error(`暂未处理该类型：${t}`);
      }
    });
  },
  /**
   * 获取标准的 BaseTable 的cols
   * @param {(string|object)[]} simpleCols 简版col
   * @returns {(string|object)[]}
   * @example ["remark", "enableStatus:status", "createTime", {tpl: 'remark'}]
   */
  getBaeTableStandardCols(simpleCols = needParam()) {
    const tpls = tableColsTpls;
    return simpleCols.map(sCol => {
      const t = typeOf(sCol);
      if (t === "String") {
        const [tpl, prop = tpl, label] = sCol.split(":");
        const Tpl = `T_${upperFirst(tpl)}`;
        return merge(tpls[Tpl], { prop, label });
      } else if (t === "Object") {
        const { tpl = "", ...rest } = sCol;
        const Tpl = `T_${upperFirst(tpl)}`;
        if (tpl && !tpls[Tpl]) throw new Error(`未找到该模板：${tpl}`);
        return merge(tpls[Tpl], rest);
      } else {
        throw new Error(`暂未处理该类型：${t}`);
      }
    });
  },
  /**
   * 获取标准的 BaseCrud 的fields和cols
   * @param {(string|object)[]} simpleFields 简版field
   * @param {(string|object)[]} simpleCols 简版col
   * @returns {(string|object)[]}
   * @example ["remark", "enableStatus:status", "createTime", {tpl: 'remark'}]
   */
  getBaseCrudStandardFieldsAndCols(simpleFields = needParam(), simpleCols = needParam()) {
    const { getFormStandardFields, getBaeTableStandardCols } = module.exports;
    return {
      fields: getFormStandardFields(simpleFields, "query"),
      cols: getBaeTableStandardCols(simpleCols),
    };
  },
};
